package online.hxstar.learn.p_http;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import online.hxstar.learn.p_http.model.Header;
import online.hxstar.learn.p_http.model.NettyMessage;

/**
 * @author huxing
 * @date 2018-12-19 12:02
 */
public class HeartBeatRespHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;
        if (message.getHeader() != null
                && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
            System.out.println("Receive client heart beat message :--->"
                    + message);
            NettyMessage hearBeat = buildHeartBeat();
            System.out.println("Send heart beat response message to client:--->"
                    + hearBeat);
            ctx.writeAndFlush(hearBeat);
        }
    }

    private NettyMessage buildHeartBeat() {
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.HEARTBEAT_RESP.value());
        message.setHeader(header);
        return message;
    }
}
